﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using WeBlog.Interfaces;

namespace WeBlog.DataContext
{
    public class InMemoryUnitOfWork : IUnitOfWork 
    {
        private readonly Dictionary<Type, IList> _dataSets;

        public InMemoryUnitOfWork()
        {
            _dataSets = new Dictionary<Type, IList>();
        }

        public void Commit()
        {
            //do nothing
        }

        public void Attach<T>(T entity) where T : class, IModel
        {
            //do nothing
        }

        public void Add<T>(T entity) where T : class, IModel
        {
            GetList<T>().Add(entity);
        }

        private List<T> GetList<T>() where T: class, IModel 
        {
            var type = typeof(T);

            if (_dataSets.ContainsKey(type) == false)
                _dataSets.Add(type, (IList) Activator.CreateInstance( typeof(List<T>)));

            return (List<T>) _dataSets[type];
        }

        public IQueryable<T> Get<T>() where T : class, IModel
        {            
            return GetList<T>().AsQueryable();
        }

        public bool Remove<T>(T item) where T : class, IModel
        {
            return GetList<T>().Remove(item);
        }

        public void Dispose()
        {
            //do nothing
        }

        public T Find<T>(params object[] keyValues) where T : class, IModel
        {
            return DbSet<T>().Find(keyValues);
        }


        public IDbSet<T> DbSet<T>() where T : class, IModel
        {
            return new InMemoryDbSet<T>(GetList<T>());
        }
    }
}
